<template>
  <a-layout class="layout-demo">
    <a-layout>
      <a-layout-header>
        <a-menu :openKeys="['1']" :selectedKeys="['0_2']" mode="horizontal">
          <a-menu-item key="0_1">
            <IconHome />
            Menu 1
          </a-menu-item>
          <a-menu-item key="0_2">
            <IconCalendar />
            Menu 2
          </a-menu-item>
        </a-menu>
      </a-layout-header>
      <a-layout style="padding: 24px">
        <a-space direction="vertical" :style="{ width: '100%' }">
          <a-descriptions title="图片翻译" layout="inline-horizontal" />
          <a-descriptions title="示例图片：" layout="inline-horizontal" />
          <a-space>
            <a-space>
              <span>图片1：</span>
              <img style="height: 80px; border-radius: 6px;cursor: pointer" :src="demoImage0" @click="onDemoImageClick(demoImage0)" />
            </a-space>
            <a-space>
              <span>图片2：</span>
              <img style="height: 80px; border-radius: 6px;cursor: pointer" :src="demoImage1" @click="onDemoImageClick(demoImage1)" />
            </a-space>
          </a-space>
          <a-upload
            :custom-request="customRequest"
            :fileList="file ? [file] : []"
            :show-file-list="false"
            @change="onChange"
            @progress="onProgress"
          >
            <template #upload-button>
              <div
                :class="`arco-upload-list-item${
                  file && file.status === 'error'
                    ? ' arco-upload-list-item-error'
                    : ''
                }`"
              >
                <div
                  class="arco-upload-list-picture custom-upload-avatar"
                  v-if="file && file.url"
                >
                  <img :src="file.url" />
                  <div class="arco-upload-list-picture-mask">
                    <IconEdit />
                  </div>
                  <a-progress
                    v-if="file.status === 'uploading' && file.percent < 100"
                    :percent="file.percent"
                    type="circle"
                    size="mini"
                    :style="{
                      position: 'absolute',
                      left: '50%',
                      top: '50%',
                      transform: 'translateX(-50%) translateY(-50%)',
                    }"
                  />
                </div>
                <div class="arco-upload-picture-card" v-else>
                  <div class="arco-upload-picture-card-text">
                    <IconPlus />
                    <div style="margin-top: 10px; font-weight: 600">Upload</div>
                  </div>
                </div>
              </div>
            </template>
          </a-upload>
          <a-space
            v-if="fileResult?.translate_image_base64"
            direction="horizontal"
            :style="{ width: '100%' }"
          >
            <img
              :style="{
                width: '400px',
              }"
              :src="file.url"
            />
            <img
              :style="{
                width: '400px',
              }"
              :src="fileResult?.translate_image_base64"
            />
          </a-space>
        </a-space>
      </a-layout>
    </a-layout>
  </a-layout>
</template>
<script>
import { defineComponent, ref } from "vue";
import { Message } from "@arco-design/web-vue";
import {
  IconHome,
  IconCalendar,
  IconEdit,
  IconPlus,
} from "@arco-design/web-vue/es/icon";
import { createClient } from "@supabase/supabase-js";

import demoImage0 from './assets/0.jpg';
import demoImage1 from './assets/1.png';
import { on } from "form-data";

const supabaseUrl = "https://irshukbofjajairxdklx.supabase.co";
const supabaseKey =
  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imlyc2h1a2JvZmphamFpcnhka2x4Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzUxMDUyMTAsImV4cCI6MjA1MDY4MTIxMH0.FN4jzTrgi88ISTg8o3mSVFnZ9YI98sDSV5Rj_UJbH7k";
const supabase = createClient(supabaseUrl, supabaseKey);

export default defineComponent({
  components: {
    IconHome,
    IconCalendar,
    IconPlus,
    IconEdit,
  },
  setup() {
    const file = ref();
    const fileResult = ref();

    const handleBase64String = async (base64String, onSuccess, onError) => {
      try {
          const { data, error } = await supabase
            .from("image_translate") // 替换为你的表名
            .insert([
              {
                image_base64: base64String,
              },
            ])
            .select("id") // 选择返回 `id`
            .single();

          if (error) throw error;

          onSuccess && onSuccess(data);

          const resultId = data.id;

          Message.success("上传图片成功");

          const loading = Message.loading({
            content: "翻译中",
            duration: 0,
          });

          while (true) {
            let isBreak = false;
            await supabase
              .from("image_translate")
              .select("*")
              .eq("id", resultId)
              .then((res) => {
                if (res?.data?.[0]?.translate_image_base64) {
                  isBreak = true;
                  fileResult.value = res.data[0];
                }
              });
            if (isBreak) {
              loading.close();
              Message.success("翻译完成");
              break;
            }
            await new Promise((resolve) => {
              setTimeout(resolve, 1000);
            });
          }
        } catch (error) {
          console.log(error);
          onError(error);
          Message.error("上传图片失败");
        }
    }

    const customRequest = (option) => {
      const { onError, onSuccess, fileItem } = option;

      const file = fileItem.file;
      const reader = new FileReader();

      reader.onload = async () => {
        handleBase64String(reader.result, onSuccess, onError);
      };

      reader.onerror = (e) => onError(e);

      reader.readAsDataURL(file); // 读取文件并转换为 Base64

      return {
        abort() {
          reader.abort && reader.abort();
        },
      };
    };

    const onChange = (_, currentFile) => {
      file.value = {
        ...currentFile,
        // url: URL.createObjectURL(currentFile.file),
      };
      fileResult.value = undefined
    };
    const onProgress = (currentFile) => {
      file.value = currentFile;
    };

    const collapsed = ref(false);
    const onCollapse = (val, type) => {
      const content = type === "responsive" ? "触发响应式收缩" : "点击触发收缩";
      Message.info({
        content,
        duration: 2000,
      });
      collapsed.value = val;
    };

    const onDemoImageClick = (image) => {
      const img = new Image();
      img.src = image; // 通过 `import` 引入的图片路径

      img.onload = () => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        canvas.width = img.width;
        canvas.height = img.height;
        ctx.drawImage(img, 0, 0);
        
        // 获取 Base64 编码的图片数据
        const base64String = canvas.toDataURL();
        debugger
        handleBase64String(base64String);
      };
    }

    return {
      file,
      fileResult,
      onChange,
      onProgress,
      collapsed,
      onCollapse,
      demoImage0,
      demoImage1,
      customRequest,
      onDemoImageClick,
      onClickMenuItem(key) {
        Message.info({ content: `You select ${key}`, showIcon: true });
      },
    };
  },
});
</script>
<style scoped>
.layout-demo {
  background: var(--color-fill-2);
  border: 1px solid var(--color-border);
}
.layout-demo :deep(.arco-layout-sider) .logo {
  height: 32px;
  margin: 12px 8px;
  background: rgba(255, 255, 255, 0.2);
}
.layout-demo :deep(.arco-layout-sider-light) .logo {
  background: var(--color-fill-2);
}
.layout-demo :deep(.arco-layout-header) {
  height: 64px;
  line-height: 64px;
  background: var(--color-bg-3);
}
.layout-demo :deep(.arco-layout-footer) {
  height: 48px;
  color: var(--color-text-2);
  font-weight: 400;
  font-size: 14px;
  line-height: 48px;
}
.layout-demo :deep(.arco-layout-content) {
  color: var(--color-text-2);
  font-weight: 400;
  font-size: 14px;
  background: var(--color-bg-3);
}
.layout-demo :deep(.arco-layout-footer),
.layout-demo :deep(.arco-layout-content) {
  display: flex;
  flex-direction: column;
  justify-content: center;
  color: var(--color-white);
  font-size: 16px;
  font-stretch: condensed;
  text-align: center;
}
</style>
